<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\DeviceSignalLog;
use App\Model\Distributors;
use App\Model\IotLog;
use App\Model\Station;
use App\Services\FileService;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Hyperf\Redis\Redis;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use PhpOffice\PhpSpreadsheet\IOFactory;

class CheckTimeoutController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Device $device;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**检查是否离线
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
   public function deviceTimeout(RequestInterface $request):ResponseInterface{
        $max_time = time();
        $members = $this->redis->zRangeByScore(Device::SIGNAL_TIME_OUT,'-inf',(string)($max_time-300));
        $this->device->whereIn('iot_sn',$members)
            ->update(['inline'=>0,'signal'=>0]);
        return $this->success($members);
   }

    /**清理一个月前信号日志
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function clearLogs(RequestInterface $request):ResponseInterface{
        $sevenDaysAgo = strtotime("-3 days", time());
        $dateSevenDaysAgo = date("Y-m-d H:i:s", $sevenDaysAgo);
        DeviceSignalLog::where('created_at','<=',$dateSevenDaysAgo)
            ->delete();
        $sevenDaysAgo = strtotime("-3 days", time());
        $dateSevenDaysAgo = date("Y-m-d H:i:s", $sevenDaysAgo);
        IotLog::where('created_at','<=',$dateSevenDaysAgo)->delete();
        return $this->success();
    }
}
